import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import GopherProps from '../objects/internal/GopherProps';
import OrderFilter from '../components/OrderFilter';
import OrderTable from '../components/OrderTable';
import OrderDetails from '../components/OrderDetails';
import './OrderFragment.css';
import { Button, Card, Space } from 'antd';
import { useTranslation } from 'react-i18next';

export default function OrderFragment(props: GopherProps) {
	const { id } = useParams<{id?: string}>();
	const {t} = useTranslation();
	const [orderSelected, setOrderSelected] = useState(false);
	const [selectedId, setSelectedId] = useState('');
	const [loading, setLoading] = useState(false);

	const onSelection = (keys: React.Key[]) => {
		console.log(keys);
		if (keys.length > 0) {
			setSelectedId(keys[0].toString());
		}
		setOrderSelected(keys.length > 0);
	};

	const openDetails = () => {
		// this part is left as an assignment
	};

	const forceClose = () => {
		setLoading(true);
		props.gopher.forceCloseOrder(selectedId).then(() => {
			setLoading(false);
		});
	};

	let child;

	if (id) {
		// detail mode
		child = (
			<OrderDetails id={id} gopher={props.gopher} />
		);
	} else {
		// table mode
		child = (
			<>
				<div className={'order-component-wrapper'}>
					<OrderFilter onSubmitButtonPressed={() => {}} gopher={props.gopher} keepAllOptions={true} />
				</div>
				<div className={'order-component-wrapper'}>
					<Card>
						<Space>
							<Button type={'primary'} disabled={!orderSelected} loading={loading} onClick={openDetails}>{t('button-order-detail')}</Button>
							<Button type={'primary'} disabled={!orderSelected} danger loading={loading} onClick={forceClose}>{t('button-order-close')}</Button>
						</Space>
					</Card>
				</div>
				<div className={'order-component-wrapper'}>
					<OrderTable gopher={props.gopher} onSelection={onSelection} />
				</div>
			</>
		);
	}

	return (
		<div className={'order-wrapper'}>
			{child}
		</div>
	);
}
